package com.nulldev.util.JVM;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.io.IOUtils;

public class Exceptions {
	public static String toString(final Throwable error) {
		final StringWriter sw = new StringWriter(IOUtils.STRING_ALLOC_BUFFER);
		final PrintWriter pw = new PrintWriter(sw);
		error.printStackTrace(pw);
		final String exceptionAsString = sw.toString();
		pw.close();
		try {
			sw.close();
		} catch (IOException e) {
		}
		return exceptionAsString;
	}

	public static String toBase64(final Throwable error) {
		return Base64.encodeBase64S(toString(error));
	}

	public static String stackTraceToString(final StackTraceElement[] stackTrace) {
		final StringBuilder sb = new StringBuilder(IOUtils.STRING_ALLOC_BUFFER);
		for (final StackTraceElement element : stackTrace) {
			sb.append("\t" + element.toString());
			sb.append("\n");
		}
		return sb.toString();
	}

	public static String getStackTrace(final StackTraceElement[] stackTrace) {
		return stackTraceToString(stackTrace);
	}
}
